from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from model import Course, Exam, StudentExam, StudentCourse, Question  # Import necessary models
from extension import db  # Assuming you're using Flask-SQLAlchemy
from datetime import datetime
from model import *


discuss_bp = Blueprint('discuss', __name__)

@discuss_bp.route('/create_comment', methods=['POST'])
@jwt_required()
def create_comment():
    data = request.json
    course_id = data.get('course_id')
    content = data.get('content')

    current_student_id = get_jwt_identity()
    print(current_student_id)
    uid = current_student_id.get('uid')

    if not course_id or not content:
        return jsonify({'error': 'Missing course_id or content'}), 400

    # 创建评论
    new_post = DiscussionPost(course_id=course_id, student_id=uid, content=content)
    db.session.add(new_post)
    db.session.commit()

    return jsonify({'message': 'Comment created successfully', 'post_id': new_post.post_id}), 200


@discuss_bp.route('/delete_comment/<post_id>', methods=['DELETE'])
@jwt_required()
def delete_comment(post_id):
    current_student_id = get_jwt_identity()
    uid = current_student_id.get('uid')

    post = DiscussionPost.query.filter_by(post_id=post_id).first()
    if not post:
        return jsonify({'error': 'Post not found'}), 404

    if post.student_id != uid:
        return jsonify({'error': 'You do not have permission to delete this post'}), 403
    try:
        # 找到相关的回复并处理
        replies = DiscussionReply.query.filter_by(post_id=post_id).all()
        for reply in replies:
            db.session.delete(reply)
        post = DiscussionPost.query.get(post_id)
        if post:
            db.session.delete(post)
        db.session.commit()

        return jsonify({"message": "Comment and related replies deleted successfully"}), 200
    except Exception as e:
        db.session.rollback()  # 回滚事务
        return jsonify({"error": str(e)}), 500


@discuss_bp.route('/create_reply/<post_id>', methods=['POST'])
@jwt_required()
def create_reply(post_id):
    data = request.json
    content = data.get('content')

    if not content:
        return jsonify({'error': 'Missing content'}), 400
    current_student_id = get_jwt_identity()
    uid = current_student_id.get('uid')

    post = DiscussionPost.query.filter_by(post_id=post_id).first()
    if not post:
        return jsonify({'error': 'Post not found'}), 404

    new_reply = DiscussionReply(post_id=post_id, student_id=uid, content=content)
    db.session.add(new_reply)
    db.session.commit()

    return jsonify({'message': 'Reply created successfully', 'reply_id': new_reply.reply_id}), 200

@discuss_bp.route('/delete_reply/<reply_id>', methods=['DELETE'])
@jwt_required()
def delete_reply(reply_id):
    current_student_id = get_jwt_identity()
    uid = current_student_id.get('uid')
    reply = DiscussionReply.query.filter_by(reply_id=reply_id).first()

    if not reply:
        return jsonify({'error': 'Reply not found'}), 404

    if reply.student_id != uid:
        return jsonify({'error': 'You do not have permission to delete this reply'}), 403

    db.session.delete(reply)
    db.session.commit()
    return jsonify({'message': 'Reply deleted successfully'}), 200


@discuss_bp.route('/get_discussion/<course_id>', methods=['GET'])
def get_course_discussion(course_id):

    posts = DiscussionPost.query.filter_by(course_id=course_id).all()


    discussion_data = []

    for post in posts:
        replies = DiscussionReply.query.filter_by(post_id=post.post_id).all()
        replies_data = [{'reply_id': reply.reply_id, 'student_id': reply.student_id, 'content': reply.content,
                         'reply_time': reply.reply_time.isoformat()} for reply in replies]

        post_data = {
            'post_id': post.post_id,
            'student_id': post.student_id,
            'content': post.content,
            'post_time': post.post_time.isoformat(),
            'replies': replies_data
        }
        discussion_data.append(post_data)


    return jsonify({'discussion': discussion_data}), 200
